import { Component } from '../core/Component.js';

/**
 * 图片组件
 */
export class Image extends Component {
  constructor(props = {}) {
    super(props);
    this.src = props.src || '';
    this.alt = props.alt || '';
    this.width = props.width || null;
    this.height = props.height || null;
    this.fit = props.fit || 'cover'; // cover, contain, fill, scale-down, none
    this.lazy = props.lazy || false; // 是否懒加载
    this.placeholder = props.placeholder || null; // 占位图片
    this.fallback = props.fallback || null; // 加载失败时的备用图片
    
    // 事件处理函数
    this.onLoad = props.onLoad || (() => {});
    this.onError = props.onError || (() => {});
    this.onClick = props.onClick || null;
    
    this.style = props.style || {};
    this.loaded = false;
    this.error = false;
  }

  /**
   * 设置图片源
   * @param {string} src 新的图片地址
   */
  setSrc(src) {
    this.src = src;
    this.loaded = false;
    this.error = false;
    
    if (this.element) {
      this.element.src = src;
      console.log('Image组件图片源已更新为:', src);
    }
  }

  /**
   * 设置替代文本
   * @param {string} alt 新的替代文本
   */
  setAlt(alt) {
    this.alt = alt;
    if (this.element) {
      this.element.alt = alt;
    }
  }

  /**
   * 设置图片尺寸
   * @param {number|string} width 宽度
   * @param {number|string} height 高度
   */
  setSize(width, height) {
    this.width = width;
    this.height = height;
    if (this.element) {
      this.applyStyle();
    }
  }

  /**
   * 重写update方法，避免重新创建DOM元素
   */
  update() {
    if (this.element) {
      this.applyStyle();
    }
  }

  applyStyle() {
    if (!this.element) return;
    
    // 基础样式
    this.element.style.display = 'block';
    this.element.style.maxWidth = '100%';
    this.element.style.height = 'auto';
    this.element.style.borderRadius = '4px';
    this.element.style.transition = 'all 0.3s ease';
    
    // 设置尺寸
    if (this.width) {
      this.element.style.width = typeof this.width === 'number' ? `${this.width}px` : this.width;
    }
    if (this.height) {
      this.element.style.height = typeof this.height === 'number' ? `${this.height}px` : this.height;
    }
    
    // 设置适应模式
    this.element.style.objectFit = this.fit;
    
    // 主题样式
    if (this.theme && this.theme.mode) {
      if (this.theme.mode === 'dark') {
        this.element.style.border = '1px solid #555';
        this.element.style.backgroundColor = '#333';
      } else {
        this.element.style.border = '1px solid #ddd';
        this.element.style.backgroundColor = '#f5f5f5';
      }
    } else {
      // 默认样式
      this.element.style.border = '1px solid #ddd';
      this.element.style.backgroundColor = '#f5f5f5';
    }
    
    // 加载状态样式
    if (!this.loaded && !this.error) {
      this.element.style.opacity = '0.6';
      this.element.style.filter = 'blur(2px)';
    } else {
      this.element.style.opacity = '1';
      this.element.style.filter = 'none';
    }
    
    // 错误状态样式
    if (this.error) {
      this.element.style.opacity = '0.5';
      this.element.style.filter = 'grayscale(100%)';
    }
    
    // 悬停效果
    if (this.onClick) {
      this.element.style.cursor = 'pointer';
      this.element.onmouseenter = () => {
        this.element.style.transform = 'scale(1.02)';
        this.element.style.boxShadow = '0 4px 8px rgba(0,0,0,0.2)';
      };
      this.element.onmouseleave = () => {
        this.element.style.transform = 'scale(1)';
        this.element.style.boxShadow = 'none';
      };
    }
    
    // 自定义样式（覆盖主题样式）
    for (const [key, value] of Object.entries(this.style)) {
      this.element.style[key] = value;
    }
  }

  /**
   * 创建占位符元素
   */
  createPlaceholder() {
    const placeholder = document.createElement('div');
    placeholder.style.width = this.width ? (typeof this.width === 'number' ? `${this.width}px` : this.width) : '200px';
    placeholder.style.height = this.height ? (typeof this.height === 'number' ? `${this.height}px` : this.height) : '150px';
    placeholder.style.backgroundColor = this.theme?.mode === 'dark' ? '#444' : '#f0f0f0';
    placeholder.style.border = this.theme?.mode === 'dark' ? '1px solid #555' : '1px solid #ddd';
    placeholder.style.borderRadius = '4px';
    placeholder.style.display = 'flex';
    placeholder.style.alignItems = 'center';
    placeholder.style.justifyContent = 'center';
    placeholder.style.color = this.theme?.mode === 'dark' ? '#aaa' : '#999';
    placeholder.style.fontSize = '14px';
    placeholder.textContent = '加载中...';
    
    return placeholder;
  }

  render() {
    this.element = document.createElement('img');
    this.element.alt = this.alt;
    
    // 如果有占位符，先显示占位符
    if (this.placeholder && !this.src) {
      this.element.src = this.placeholder;
    } else if (this.src) {
      this.element.src = this.src;
    }
    
    // 懒加载设置
    if (this.lazy) {
      this.element.loading = 'lazy';
    }
    
    // 绑定加载事件
    this.element.addEventListener('load', (event) => {
      this.loaded = true;
      this.error = false;
      this.applyStyle();
      
      if (this.onLoad) {
        this.onLoad.call(this, event);
      }
      
      console.log('Image组件加载成功:', this.src);
    });
    
    // 绑定错误事件
    this.element.addEventListener('error', (event) => {
      this.loaded = false;
      this.error = true;
      
      // 如果有备用图片，尝试加载备用图片
      if (this.fallback && this.element.src !== this.fallback) {
        console.log('Image组件加载失败，尝试备用图片:', this.fallback);
        this.element.src = this.fallback;
        return;
      }
      
      this.applyStyle();
      
      if (this.onError) {
        this.onError.call(this, event);
      }
      
      console.error('Image组件加载失败:', this.src);
    });
    
    // 绑定点击事件
    if (this.onClick) {
      this.element.addEventListener('click', (event) => {
        this.onClick.call(this, event);
      });
    }
    
    this.applyStyle();
    return this.element;
  }
} 